<template>
  <div class="app-container">
    <el-card style="margin-bottom: 20px">
      <el-form ref="saleOrderFormRef" :model="saleOrderQueryParams" inline>
        <el-form-item label="计划单号" prop="orderNo">
          <el-input
            v-model="saleOrderQueryParams.orderNo"
            placeholder="计划单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-select
            v-model="saleOrderQueryParams.customerName"
            placeholder="请选择客户名称"
          >
            <el-option
              v-for="item in customerList"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交货日期" prop="deliverAttr">
          <el-date-picker
            v-model="saleOrderQueryParams.deliverAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-select
            v-model="saleOrderQueryParams.applyUser"
            placeholder="请选择申请人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyAttr">
          <el-date-picker
            v-model="saleOrderQueryParams.applyAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select
            v-model="saleOrderQueryParams.applyStatus"
            placeholder="请选择申请状态"
          >
            <el-option label="未提交" value="未提交"></el-option>
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="已审核" value="已审核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="approveUser">
          <el-select
            v-model="saleOrderQueryParams.approveUser"
            placeholder="请选择审核人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核时间" prop="approveAttr">
          <el-date-picker
            v-model="saleOrderQueryParams.approveAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态" prop="approveStatus">
          <el-select
            v-model="saleOrderQueryParams.approveStatus"
            placeholder="请选择审核状态"
          >
            <el-option label="通过" value="通过"></el-option>
            <el-option label="驳回" value="驳回"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSaleOrderList">查询</el-button>
          <el-button @click="resetSaleOrderForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div style="margin-bottom: 20px">
        <el-button @click="handleAdd" type="success">新增</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </div>
      <el-table
        @selection-change="selectSaleOrderRow"
        :data="saleOrderList"
        style="width: 100%"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          v-for="item in saleOrderColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        >
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; justify-content: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="saleOrderPager.page"
        :page-sizes="[8, 10, 30, 30]"
        :page-size="saleOrderPager.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="saleOrderTotal"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      center
      :visible.sync="editVisible"
      title="修改销售订单"
      width="1200px"
      @close="closeEdit"
    >
      <el-form inline>
        <el-form-item label="客户名称">
          <el-input
            v-if="updateSaleOrderRow.customer"
            v-model="updateSaleOrderRow.customer.name"
            disabled
            placeholder="请输入客户名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectSaleCustomer">选择</el-button>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="addDetailListUp">添加</el-button>
      <el-table :data="detailList" style="width: 100%">
        <el-table-column label="序号" v-slot="{ $index }">
          {{ $index + 1 }}
        </el-table-column>
        <el-table-column label="产品" v-slot="{ $index, row }" width="150">
          <!-- {{ row.material.name }} -->
          <el-button type="primary" @click="selectMaterial($index, row)"
            >选择</el-button
          >
        </el-table-column>
        <el-table-column
          v-for="item in dattailColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        >
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="addDetailList(scope.$index, scope.row)"
              >添加</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="delDetailList(scope.index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="closeEdit">取消</el-button>
          <el-button type="primary" @click="submitEditSaleOrder"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      center
      :visible.sync="addVisible"
      title="添加销售订单"
      width="1200px"
      @close="addEdit"
    >
      <el-form :model="addForm" inline>
        <el-form-item label="客户名称">
          <el-input
            v-model="addForm.customerName"
            disabled
            placeholder="请输入客户名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectSaleCustomer">选择</el-button>
        </el-form-item>
        <el-form-item label="交货日期" prop="deliverDate">
          <el-date-picker
            v-model="addForm.deliveryDate"
            type="date"
            placeholder="选择交货日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="addForm.remark"
            placeholder="备注"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectSaleCustomer">选择</el-button>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="addDetailListUp">添加</el-button>
      <el-table :data="detailList" style="width: 100%">
        <el-table-column label="序号" v-slot="{ $index }">
          {{ $index + 1 }}
        </el-table-column>
        <el-table-column label="产品" v-slot="{ $index, row }" width="150">
          <!-- {{ row.material.name }} -->
          <el-button type="primary" @click="selectMaterial($index, row)"
            >选择</el-button
          >
        </el-table-column>
        <el-table-column
          v-for="item in dattailColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        >
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="addDetailList(scope.$index, scope.row)"
              >添加</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="delDetailList(scope.index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="closeEdit">取消</el-button>
          <el-button type="primary" @click="submitAddSaleOrder">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      center
      :visible.sync="materialVisible"
      title="选择物料档案"
      width="1200px"
    >
      <el-row>
        <el-col :span="4">
          <el-tree
            :data="materialCategoryData"
            :props="{ label: 'name' }"
            @node-click="materialCategoryChange"
          ></el-tree>
        </el-col>
        <el-col :span="20">
          <el-table :data="materialData">
            <el-table-column
              v-for="item in materialColumn"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            ></el-table-column>
            <el-table-column label="操作" v-slot="{ row }">
              <el-button type="primary" @click="submitSelectMaterial(row)"
                >选择</el-button
              >
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog center :visible.sync="saleCustomerVisible" title="选择销售客户">
      <el-card style="margin-bottom: 20px">
        <el-form
          :inline="true"
          :model="customerQueryParams"
          ref="customerFormRef"
          class="demo-form-inline"
        >
          <el-form-item label="客户名称" prop="name">
            <el-input
              v-model="customerQueryParams.name"
              placeholder="请输入客户名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input
              v-model="customerQueryParams.contact"
              placeholder="请输入联系人"
            ></el-input>
          </el-form-item>
          <el-form-item label="客户分类" prop="category">
            <el-select
              v-model="customerQueryParams.category"
              placeholder="请选择客户分类"
            >
              <el-option label="核心客户" value="核心客户"></el-option>
              <el-option label="普通客户" value="普通客户"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchCustomerList"
              >查询</el-button
            >
            <el-button @click="resetCustomerList">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="customerList" style="width: 100%">
          <el-table-column
            v-for="item in customerColumn"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
          >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="selectCustomer(scope.row)"
                >选择</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="display: flex; justify-content: right"
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :current-page="customerPager.page"
          :page-sizes="[4, 8, 10, 20]"
          :page-size="customerPager.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="customerTotal"
        >
        </el-pagination>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { getSaleOrderList, getCustomerList, editSaleOrder, delSaleOrder, addSaleOrder, getApplyApproveUserList } from '@/api_zc/scm/sale-management/sale-order'
import { getMaterialCategoryList, getMaterialList } from '@/api_zc/mes/product-modeling'
export default {
  mounted () {
    this.getSaleOrderList()
    this.getCustomerList()
    this.getMaterialCategoryList()
    this.getMaterialList()
    this.getApplyApproveUserList()
  },
  data () {
    return {
      isAdd: true,
      addForm: {
        deliveryDate: '',
        customerName: '',
        remark: ''
      },
      selectSaleOrderRowData: [],
      materialData: [],
      updateSaleOrderRow: {},
      materialCategoryData: [],
      materialVisible: false,
      materialCategoryPid: 0,
      updateMaterialId: 0,
      materialColumn: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '物料编码',
          prop: 'code'
        },
        {
          label: '物料名称',
          prop: 'name'
        },
        {
          label: '型号',
          prop: 'model'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '单位',
          prop: 'unit'
        },
        {
          label: '单价',
          prop: 'price'
        },
        {
          label: '类型',
          prop: 'category.name'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],
      userList: [],
      editVisible: false,
      saleCustomerVisible: false,
      saleOrderList: [],
      saleOrderColumn: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '订单编号',
          prop: 'orderNo'
        },
        {
          label: '客户名称',
          prop: 'customer.name'
        },
        {
          label: '联系人',
          prop: 'customer.contact'
        },
        {
          label: '联系方式',
          prop: 'customer.telephone'
        },
        {
          label: '金额合计',
          prop: 'totalAmount'
        },
        {
          label: '交货日期',
          prop: 'deliveryDate'
        },
        {
          label: '申请人',
          prop: 'applyUser.realName'
        },
        {
          label: '申请时间',
          prop: 'applyTime'
        },
        {
          label: '申请状态',
          prop: 'applyStatus'
        },
        {
          label: '审核人',
          prop: 'approveUser.realName'
        },
        {
          label: '审核时间',
          prop: 'approveTime'
        },
        {
          label: '审核状态',
          prop: 'approveStatus'
        },
      ],
      saleOrderTotal: 0,
      saleOrderPager: {
        page: 1,
        limit: 8
      },
      searchCustomerForm: {},
      customerList: [],
      customerColumn: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '客户名称',
          prop: 'name'
        },
        {
          label: '公司地址',
          prop: 'address'
        },
        {
          label: '联系人',
          prop: 'contact'
        },
        {
          label: '联系电话',
          prop: 'telephone'
        },
        {
          label: '客户分类',
          prop: 'category'
        },
        {
          label: '信用等级',
          prop: 'creditLevel'
        },
      ],
      customerPager: {
        page: 1,
        limit: 8
      },
      customerQueryParams: {
        name: '',
        contact: '',
        category: ''
      },
      customerTotal: 0,
      saleCustomer: {},
      detailList: [],
      dattailColumn: [
        {
          label: '型号',
          prop: 'material.model'
        },
        {
          label: '规格',
          prop: 'material.specification'
        },
        {
          label: '单位',
          prop: 'material.unit'
        },
        {
          label: '单价',
          prop: 'material.price'
        },
        {
          label: '订货数量',
          prop: 'quantity'
        },
        {
          label: '金额',
          prop: 'amount'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],
      saleOrderQueryParams: {
        orderNo: '',
        customerName: '',
        deliverStartDate: '',
        deliverEndDate: '',
        deliverAttr: [],
        applyUser: '',
        applyStatus: '',
        applyStartTime: '',
        applyEndTime: '',
        applyAttr: '',
        approveUser: '',
        approveStartTime: '',
        approveEndTime: '',
        approveAttr: '',
        approveStatus: ''
      },
      addVisible: false
    }
  },
  methods: {
    searchCustomerList () {
      this.getCustomerList()
    },
    resetCustomerList () {
      this.$refs.customerFormRef.resetFields()
      this.getCustomerList()
    },
    selectCustomer (row) {
      Object.assign(this.saleCustomer, row)
      this.updateSaleOrderRow.customer = this.saleCustomer
      this.saleCustomerVisible = false
      this.addForm.customerName = this.updateSaleOrderRow.customer.name
    },
    handleEdit (row) {
      this.isAdd = false
      this.editVisible = true
      this.updateSaleOrderRow = row
      console.log(this.updateSaleOrderRow)
      this.detailList = JSON.parse(JSON.stringify(row.detailList))
    },
    handleDelete (row) {
      let orderNo, ids
      if (row.id) {
        orderNo = row.orderNo
        ids = [row.id]
      } else {
        orderNo = this.selectSaleOrderRowData.map(item => item.orderNo).join(',')
        ids = this.selectSaleOrderRowData.map(item => item.id)
      }
      if (!ids.length) {
        return this.$message.error('请选择要删除的数据项')
      }
      this.$confirm(`是否确认删除销售订单编号为${orderNo}的数据项？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { code, msg } = await delSaleOrder({ ids })
        if (code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getSaleOrderList()
        } else {
          this.$message({
            type: 'error',
            message: msg
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    onSubmit () {
      console.log('submit!')
    },
    resetSaleOrderForm () {
      this.$refs.saleOrderFormRef.resetFields()
      this.saleOrderQueryParams.deliverStartDate = ''
      this.saleOrderQueryParams.deliverEndDate = ''
      this.saleOrderQueryParams.applyStartTime = ''
      this.saleOrderQueryParams.applyEndTime = ''
      this.saleOrderQueryParams.approveStartTime = ''
      this.saleOrderQueryParams.approveEndTime = ''
      this.getSaleOrderList()
    },
    selectSaleCustomer () {
      this.saleCustomerVisible = true
    },
    async getSaleOrderList () {
      this.saleOrderQueryParams.deliverStartDate = this.saleOrderQueryParams.deliverAttr[0]
      this.saleOrderQueryParams.deliverEndDate = this.saleOrderQueryParams.deliverAttr[1]
      this.saleOrderQueryParams.applyStartTime = this.saleOrderQueryParams.applyAttr[0]
      this.saleOrderQueryParams.applyEndTime = this.saleOrderQueryParams.applyAttr[1]
      this.saleOrderQueryParams.approveStartTime = this.saleOrderQueryParams.approveAttr[0]
      this.saleOrderQueryParams.approveEndTime = this.saleOrderQueryParams.approveAttr[1]
      const { data: { total, content } } = await getSaleOrderList({ ...this.saleOrderQueryParams, page: this.saleOrderPager.page, limit: this.saleOrderPager.limit })
      this.saleOrderList = content
      this.saleOrderTotal = total
    },
    async getCustomerList () {
      const { data: { total, content } } = await getCustomerList({ ...this.customerQueryParams, page: this.customerPager.page, limit: this.customerPager.limit })
      this.customerList = content
      this.customerTotal = total
    },
    async getApplyApproveUserList () {
      const { data } = await getApplyApproveUserList()
      this.userList = data
    },
    async getMaterialCategoryList () {
      const { data } = await getMaterialCategoryList()
      const array = [
        {
          children: data,
          id: 0,
          name: '目录'
        }
      ]
      this.materialCategoryData = array
      console.log(this.materialCategoryData)
    },
    async getMaterialList () {
      const { data: { content } } = await getMaterialList({ pid: this.materialCategoryPid })
      this.materialData = content
    },
    materialCategoryChange ({ id }) {
      this.materialCategoryPid = id
      this.getMaterialList()
    },
    handleSizeChange (val) {
      this.saleOrderPager.limit = val
      this.getSaleOrderList()
    },
    handleCurrentChange (val) {
      this.saleOrderPager.page = val
      this.getSaleOrderList()
    },
    handleSizeChange2 (val) {
      this.customerPager.limit = val
      this.getCustomerList()
    },
    handleCurrentChange2 (val) {
      this.customerPager.page = val
      this.getCustomerList()
    },
    selectMaterial (index) {
      this.materialVisible = true
      this.updateMaterialId = index
    },
    submitSelectMaterial (row) {
      const newRow = JSON.parse(JSON.stringify(row))
      if (newRow instanceof Object) {
        delete newRow.category
      }
      console.log(newRow)
      this.detailList[this.updateMaterialId].material = newRow
      this.materialVisible = false
    },
    addDetailList (index, row) {
      const emptyRow = JSON.parse(JSON.stringify(row))
      Object.keys(emptyRow).forEach(key => {
        emptyRow[key] = ''
      })
      this.detailList.splice(index + 1, 0, emptyRow)
    },
    addDetailListUp () {
      this.detailList.push({
        amount: '',
        material: {
          name: "",
          model: "",
          specification: "",
          unit: "",
          price: ""
        },
        quantity: 1,
        remark: ""
      })
    },
    delDetailList (index) {
      this.detailList.splice(index, 1)
    },
    closeEdit () {
      this.editVisible = false
      this.addVisible = false
    },
    handleAdd () {
      this.addVisible = true
      this.isAdd = true
    },
    addEdit () {
      this.addVisible = false
    },
    async submitAddSaleOrder () {
      this.updateSaleOrderRow.detailList = this.detailList
      this.updateSaleOrderRow.customer = this.saleCustomer
      const { id, customer: { id: customerId }, detailList } = this.updateSaleOrderRow
      const data = {
        customerId,
        remark: this.addForm.remark,
        deliveryDate: this.addForm.deliveryDate,
        detailList: detailList.filter(item => item.material?.name)
      }
      const { code, msg } = await addSaleOrder(data)
      if (code == 200) {
        this.$message.success('添加成功')
        this.addVisible = false
        this.getSaleOrderList()
      } else {
        this.$message.error(msg)
      }
    },
    async submitEditSaleOrder () {
      this.updateSaleOrderRow.detailList = this.detailList
      this.updateSaleOrderRow.customer = this.saleCustomer
      const { id, remark, customer: { id: customerId }, detailList } = this.updateSaleOrderRow
      const data = {
        id,
        customerId,
        remark,
        detailList: detailList.filter(item => item.material?.name)
      }
      const { code, msg } = await editSaleOrder(data)
      if (code == 200) {
        this.$message.success('修改成功')
        this.editVisible = false
        this.getSaleOrderList()
      } else {
        this.$message.error(msg)
      }
    },
    selectSaleOrderRow (selection) {
      this.selectSaleOrderRowData = selection
    },
  }
}
</script>

<style>
</style>